package cn.caplike.demo.rabbitmq.api.exchange.topic;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;
import org.springframework.amqp.core.ExchangeTypes;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

/**
 * @author LiKe
 * @version 1.0.0
 * @date 2020-02-18 14:44
 */
public class Consumer4TopicExchange {

    public static void main(String[] args) throws IOException, TimeoutException {
        // 创建一个链接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("111.229.226.114");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");

        // 通过链接工厂创建连接
        Connection connection = connectionFactory.newConnection();

        // 通过连接创建一个 Channel
        Channel channel = connection.createChannel();

        String exchangeName = "test_topic_exchange";
        String exchangeType = ExchangeTypes.TOPIC;
        String queueName = "test_topic_queue";
        // # 匹配一个或者多个词, * 匹配一个词
        String routingKey = "user.#";
        // 声明交换机
        channel.exchangeDeclare(exchangeName, exchangeType, false, true, false, null);
        // 声明队列
        channel.queueDeclare(queueName, false, false, true, null);
        // 绑定
        channel.queueBind(queueName, exchangeName, routingKey);

        // 声明一个队列
        System.out.println("Waiting for message ...");

        // https://www.rabbitmq.com/tutorials/tutorial-one-java.html
        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
            System.out.println("Received '" + message + "'");
        };
        channel.basicConsume(queueName, true, deliverCallback, System.out::println);
    }
}
